<?php

namespace App\Http\Controllers\Business\App\Common;

use App\Models\City;
use App\Models\FirstClass;
use App\Models\Oss;
use App\Models\Province;
use App\Models\SecondClass;
use App\Models\District;
use App\Models\BusinessArea;
use App\Models\Shop;
use App\Models\User;
use App\Models\Feedback;

class Common
{
    //获取已开通的城市
    public static function getAllOpenedCities() {
        $cities = City::where('status', 1)->get();
        //获取已开通的简写 数组
        $letterLists = [];
        foreach($cities as $city) {
            $letter = $city['letter'];
            if(Shop::where('cityid', $city['id'])->where('status', 1)->count() > 0) {
                if (!in_array($letter, $letterLists)) {
                    array_push($letterLists, $letter);
                }
            }
        }
        $lists = [];
        foreach($letterLists as $letter) {
            $cityLists = [];
            foreach($cities as $city) {
                if($letter != $city['letter']) {
                    continue;
                }
                $cityId = $city['id'];
                if(Shop::where('cityid', $cityId)->where('status', 1)->count() > 0) {
                    array_push($cityLists, [
                        'cityid' => $city['id'],
                        'cityname' => $city['name']
                    ]);
                }
            }
            array_push($lists, [
                'letter' => $letter,
                'cities' => $cityLists
            ]);
        }
        return ['status'=>'success', 'message'=>'获取城市成功', 'data'=>$lists];
    }
    //获取城市，版本号v15
    public static function getCitiesByV15Version() {
        $cities = City::where('status', 1)->select('id', 'letter', 'name', 'status')->orderBy('letter', 'asc')->get();
        //获取已开通的简写 数组
        $letterLists = [];
        foreach($cities as $city) {
            $letter = $city['letter'];
            if (!in_array($letter, $letterLists)) {
                array_push($letterLists, $letter);
            }
        }
        $lists = [];
        foreach($letterLists as $letter) {
            $cityLists = [];
            foreach($cities as $city) {
                if($letter != $city['letter']) {
                    continue;
                }
                $cityId = $city['id'];
                if((Shop::where('cityid', $cityId)->where('status', 1)->count() > 0) && ($city['status']==1)) {
                    if(($cityId == 4) && (date('Y-m-d H:i:s') < '2017-06-18 00:00:00')) {
                        //TODO 厦门6月18号上线， 以后来删除
                        $status = 0;
                    } else {
                        $status = 1;
                    }
                } else {
                    $status = 0;
                }
                array_push($cityLists, [
                    'cityid' => $city['id'],
                    'cityname' => $city['name'],
                    'status' => $status
                ]);
            }
            array_push($lists, [
                'letter' => $letter,
                'cities' => $cityLists
            ]);
        }
        return ['status'=>'success', 'data'=>$lists];
    }
    //获取所有有商家的城市
    public static function getHavingShopCities() {
        $lists = [];
        $cities = City::where('status', 1)->get();
        foreach($cities as $city) {
            if(Shop::where('cityid', $city['id'])->where('status', 1)->count() > 0) {
                array_push($lists, $city);
            }
        }
        return ['status'=>'success', 'message'=>'获取信息成功', 'data'=>$lists];
    }
    //获取所有的城市
    public static function AllCities() {
        $cities = City::where('status', 1)->get();
        return ['status'=>'success', 'message'=>'获取信息成功', 'data'=>$cities];
    }
    //获取商家一级,二级分类
    public static function getClass() {
        $lists = [];
        $firstClassLists = FirstClass::where('status', 1)->get();
        foreach($firstClassLists as $firstClassList) {
            $firstClassId = $firstClassList['id'];
            $list['id'] = $firstClassId;
            $list['isfirstclass'] = 1;
            $list['name'] = $firstClassList['name'];
            $list['logo'] = $firstClassList['logo'];
            $list['status'] = $firstClassList['status'];
            $secondClassLists = SecondClass::where('firstclassid', $firstClassId)->orderBy('sort', 'asc')->get();
            $content = [];
            foreach($secondClassLists as $secondClassList) {
                $secondClassId = $secondClassList['id'];
                $secondClassName = $secondClassList['name'];
                $secondClassStatus = $secondClassList['status'];
                array_push($content, [
                    'id' => $secondClassId,
                    'name' => $secondClassName,
                    'status' => $secondClassStatus,
                    'isfirstclass' => 0
                ]);
            }
            $list['childlists'] = $content;
            array_push($lists, $list);
        }
        return ['status'=>'success', 'message'=>'获取分类信息成功', 'data'=>$lists ];
    }
    //获取晚九点的分类(酒店，ktv)
    public static function getNightEventClass() {
        $lists = [];
        //酒店
        $hotelId = 4;
        $hotelCount = Shop::where(['status'=>1, 'nightevent'=>1, 'firstclassid'=>$hotelId])->get()->count();
        if($hotelCount > 0) {
            $list['id'] = $hotelId;
            $list['name'] = '酒店';
            $list['logo'] = '';
            $list['status'] = 1;
            $list['isfirstclass'] = 1;
            $secondClassLists = SecondClass::where('firstclassid', $hotelId)->get();
            $content = [];
            foreach($secondClassLists as $secondClassList) {
                $secondClassId = $secondClassList['id'];
                $secondClassName = $secondClassList['name'];
                $secondClassStatus = $secondClassList['status'];
                array_push($content, [
                    'id' => $secondClassId,
                    'name' => $secondClassName,
                    'status' => $secondClassStatus,
                ]);
            }
            $list['childlists'] = $content;
            array_push($lists, $list);
        }
        //KTV
        $ktvId = 9;
        $ktvCount = Shop::where(['status'=>1, 'nightevent'=>1, 'secondclassid'=>$ktvId])->get()->count();
        if($ktvCount > 0) {
            $list['id'] = $ktvId;
            $list['name'] = 'KTV';
            $list['logo'] = '';
            $list['status'] = 1;
            $list['isfirstclass'] = 0;
            $list['childlists'] = [];
            array_push($lists, $list);
        }
        return ['status'=>'success', 'message'=>'获取分类信息成功', 'data'=>$lists ];
    }
    //获取商圈
    public static function getDistrictAndBusinessArea($cityId) {
        if(!$cityId) {
            return ['status'=>'failed', 'message'=>'无效参数'];
        }
        $lists = [];
        $districtLists = District::where('cityid', $cityId)->where('status',1)->orderBy('sort', 'asc')->get();
        foreach($districtLists as $districtList) {
            $districtId = $districtList['id'];
            $list['id'] = $districtId;
            $list['name'] = $districtList['name'];
            $list['letter'] = $districtList['letter'];
            $list['status'] = $districtList['status'];
            $secondLists = [];
            $businessAreaLists = BusinessArea::where('districtid', $districtId)->where('status',1)->get();
            foreach($businessAreaLists as $businessAreaList) {
                $secondList['id'] = $businessAreaList['id'];
                $secondList['name'] = $businessAreaList['name'];
                $secondList['letter'] = $businessAreaList['letter'];
                $secondList['status'] = $businessAreaList['status'];
                array_push($secondLists, $secondList);
            }
            $list['childlists'] = $secondLists;
            array_push($lists, $list);
        }
        return ['status'=>'success', 'message'=>'获取信息成功', 'data'=>$lists];
    }
    //通过ip获取高德地图的位置范围
    public static function getPositionByIp($ip) {
        $mapKey = "77095839e7a388d0a59f32ae121ea2f5";
        $url = "http://restapi.amap.com/v3/ip?key=" . $mapKey . "&ip=" . $ip;
        $content = file_get_contents($url);
        $result = json_decode($content,true);
        if(!isset($result['rectangle'])) {
            return ['status'=>'failed', 'message'=>'获取经纬度失败'];
        } else {
            $positionArray = [];
            $rectangle = $result['rectangle'];
            $lists = explode(';', $rectangle);
            foreach($lists as $list) {
                $arr = explode(',', $list);
                $longtitude = $arr[0];
                $latitude = $arr[1];
                array_push($positionArray, [
                    'longtitude' => $longtitude,
                    'latitude' => $latitude
                ]);
            }
            return ['status'=>'success', 'message'=>'获取信息成功', 'data'=>$positionArray];
        }
    }
    //通过IP获取城市id
    public static function getCityIdByIp($ip) {
        $mapKey = "77095839e7a388d0a59f32ae121ea2f5";
        $url = "http://restapi.amap.com/v3/ip?key=" . $mapKey . "&ip=" . $ip;
        $content = file_get_contents($url);
        $result = json_decode($content,true);
        if(!isset($result['city'])) {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        $cityName = $result['city'];
        if($cityName) {
            $city = City::where('name', $cityName)->first();
        } else {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        if($city) {
            $cityId = $city->id;
            $status = $city->status;
        } else {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        $data = [
            'cityid'=>$cityId,
            'cityname' => $cityName,
            'status' => $status
        ];
        return ['status'=>'success', 'message'=>'获取信息成功', 'data'=>$data];
    }
    //意见反馈
    public static function feedback($userId, $content, $osVersion='', $phoneType='', $versionCode='',$cityId='') {
        if(!$userId || !$content) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $user = User::where('id', $userId)->select('nickname', 'mobile')->first();
        if($user) {
            Feedback::create([
                'userid' => $userId,
                'username' => $user['nickname'],
                'mobile' => $user['mobile'],
                'content' => $content,
                'status' => 0,
                'type' => 'user',
                'osversion' => $osVersion,
                'phonetype' => $phoneType,
                'versioncode' => $versionCode,
                'cityid'=>$cityId,
            ]);
            return ['status'=>'success', 'message'=>'提交成功'];
        } else {
            return ['status'=>'failed', 'message'=>'提交失败'];
        }
    }
    //通过日期判断是不是节假日,返回参数：工作日对应结果为 0, 休息日对应结果为 1, 节假日对应的结果为 2；
    public static function isHoliday($day) {
        $month = date('Ym');
        $ch = curl_init();
        $url = 'http://apis.baidu.com/xiaogg/holiday/holiday?d=201609';
        $header = array(
            'apikey: 5c526700f8145c01e24436064654a67f',
        );
        // 添加apikey到header
        curl_setopt($ch, CURLOPT_HTTPHEADER  , $header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // 执行HTTP请求
        curl_setopt($ch , CURLOPT_URL , $url);
        $res = curl_exec($ch);
        return json_decode($res);
    }

    public static function getStsOssAuth() {
        $oss = Oss::getStsAuth();
        $data['AccessKeySecret'] = $oss['AccessKeySecret'];
        $data['AccessKeyId'] = $oss['AccessKeyId'];
        $data['SecurityToken'] = $oss['SecurityToken'];
        return ['status'=>'success', 'data'=>$data];
    }
}